#include "RunDlg.h"
#include <QLineEdit>
#include <QTableWidget>
#include <QVBoxLayout>
#include <QDebug>
#include <QProcess>
#include <QTimer>
#include "ShortCut.h"
#include "LineEdit.h"
#include "TableWidget.h"

RunDlg::RunDlg(QWidget *parent) :
    QDialog(parent)
{
    lineEdit = new LineEdit(this);
    tableWidget = new TableWidget(this);
    tableWidget->setColumnCount(3);
    tableWidget->setRowCount(10);

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(lineEdit);
    layout->addWidget(tableWidget);
    setLayout(layout);

    shortCuts = new ShortCutVec();
    shortCuts->loadItems("a.txt");

    timer = new QTimer(this);

    connect(timer, SIGNAL(timeout()),
            this, SLOT(hide()));

    connect(lineEdit, SIGNAL(textChanged(QString)),
            this, SLOT(commandUpdate(QString)));

    connect(lineEdit, SIGNAL(commandSelect(int)),
            this, SLOT(commandSelect(int)));
}

void RunDlg::resetTimer()
{
    timer->stop();
    timer->start(5000);
}

void RunDlg::show()
{
    resetTimer();
    QDialog::show();
}

void RunDlg::commandUpdate(QString str)
{
    resetTimer();
    tableWidget->clear();
    count = 0;
    for (auto it = shortCuts->begin(); it!=shortCuts->end(); it++) {
        PItem pItem = *it;
        if (pItem->shortCut.startsWith(str, Qt::CaseInsensitive) ) {
            QTableWidgetItem* tItem;
            tItem = new QTableWidgetItem(pItem->shortCut);
            tableWidget->setItem(count, 0, tItem);
            tItem = new QTableWidgetItem(pItem->name);
            tableWidget->setItem(count, 1, tItem);
            tItem = new QTableWidgetItem(pItem->cmdLine);
            tableWidget->setItem(count, 2, tItem);
            count++;
        }
    }
}
void RunDlg::commandSelect(int key)
{
    if (key == Qt::Key_0)
        key += 10;
    key -= Qt::Key_1;
    if (key >= count)
        return;
    QString str = tableWidget->item(key, 2)->text();
    qDebug() << key << str;
    QProcess::execute(str);
}
